import HouseFormModal from '@/components/HouseFormModal';
import { getHouseDetail, type HouseDetailData } from '@/services/house-detail';
import {
  ArrowLeftOutlined,
  DollarOutlined,
  EditOutlined,
  FileTextOutlined,
  HistoryOutlined,
  HomeOutlined,
  SwapOutlined,
  ToolOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useNavigate, useParams } from '@umijs/max';
import {
  Button,
  Card,
  Descriptions,
  Modal,
  Space,
  Table,
  Tabs,
  Tag,
  message,
} from 'antd';
import { useEffect, useState } from 'react';

export default () => {
  const params = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [houseData, setHouseData] = useState<HouseDetailData | null>(null);

  // 编辑弹窗状态
  const [houseFormModalVisible, setHouseFormModalVisible] = useState(false);

  // 认证和核验弹窗状态
  const [authModalVisible, setAuthModalVisible] = useState(false);
  const [verifyModalVisible, setVerifyModalVisible] = useState(false);

  // 获取房屋详情数据
  useEffect(() => {
    const fetchHouseDetail = async () => {
      if (!params.id) return;

      setLoading(true);
      try {
        const data = await getHouseDetail(params.id);
        setHouseData(data);
      } catch (error) {
        message.error('获取房屋详情失败');
        console.error('获取房屋详情失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchHouseDetail();
  }, [params.id]);

  const handleBack = () => {
    navigate(-1);
  };

  const handleEditBasicInfo = () => {
    setHouseFormModalVisible(true);
  };

  const handleEditRentalInfo = () => {
    navigate(`/house_manage/rental_form?id=${params.id}`);
  };

  const handleHouseFormSuccess = () => {
    setHouseFormModalVisible(false);
    message.success('房屋基础信息更新成功');
    // 这里可以重新加载数据
  };

  // 认证相关处理函数
  const handleAuthClick = () => {
    setAuthModalVisible(true);
  };

  const handleGoAuth = () => {
    message.info('跳转到认证页面');
    // 这里可以跳转到认证页面
  };

  // 核验相关处理函数
  const handleVerifyClick = () => {
    setVerifyModalVisible(true);
  };

  const handleGoVerify = () => {
    message.info('跳转到核验页面');
    // 这里可以跳转到核验页面
  };

  // 合同表格列配置
  const contractColumns = [
    {
      title: '合同类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '租户姓名',
      dataIndex: 'tenantName',
      key: 'tenantName',
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      key: 'endDate',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `¥${amount}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '生效中' ? 'green' : 'default'}>{status}</Tag>
      ),
    },
    {
      title: '签约时间',
      dataIndex: 'signDate',
      key: 'signDate',
    },
  ];

  // 账单表格列配置
  const billColumns = [
    {
      title: '账单类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `¥${amount}`,
    },
    {
      title: '到期时间',
      dataIndex: 'dueDate',
      key: 'dueDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '已支付' ? 'green' : 'orange'}>{status}</Tag>
      ),
    },
    {
      title: '支付时间',
      dataIndex: 'payDate',
      key: 'payDate',
      render: (payDate: string | null) => payDate || '-',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
  ];

  // 维修记录表格列配置
  const repairColumns = [
    {
      title: '维修类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '报修时间',
      dataIndex: 'reportDate',
      key: 'reportDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '已完成' ? 'green' : 'processing'}>{status}</Tag>
      ),
    },
    {
      title: '完成时间',
      dataIndex: 'completeDate',
      key: 'completeDate',
    },
    {
      title: '费用',
      dataIndex: 'cost',
      key: 'cost',
      render: (cost: number) => `¥${cost}`,
    },
    {
      title: '维修师傅',
      dataIndex: 'repairman',
      key: 'repairman',
    },
  ];

  // 转租&退租申请表格列配置
  const transferColumns = [
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '租户姓名',
      dataIndex: 'tenantName',
      key: 'tenantName',
    },
    {
      title: '申请时间',
      dataIndex: 'applyDate',
      key: 'applyDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '待审核' ? 'orange' : 'default'}>{status}</Tag>
      ),
    },
    {
      title: '原因',
      dataIndex: 'reason',
      key: 'reason',
    },
    {
      title: '预期时间',
      dataIndex: 'expectedDate',
      key: 'expectedDate',
    },
  ];

  // 操作日志表格列配置
  const logColumns = [
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
  ];

  if (!houseData) {
    return <PageContainer loading={loading} />;
  }

  return (
    <PageContainer
      loading={loading}
      header={{
        title: (
          <Space>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={handleBack}
            >
              返回
            </Button>
            <span>房屋详情</span>
          </Space>
        ),
      }}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 房屋基础信息 */}
        <Card
          title={
            <Space>
              <HomeOutlined />
              <span>房屋基础信息</span>
            </Space>
          }
          extra={
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={handleEditBasicInfo}
            >
              编辑
            </Button>
          }
        >
          <Descriptions column={3} bordered>
            <Descriptions.Item label="城市">
              {houseData.basicInfo.cityName}
            </Descriptions.Item>
            <Descriptions.Item label="小区名称">
              {houseData.basicInfo.communityName}
            </Descriptions.Item>
            <Descriptions.Item label="房屋信息">
              {houseData.basicInfo.houseInfo}
            </Descriptions.Item>
            <Descriptions.Item label="详细地址" span={2}>
              {houseData.basicInfo.address}
            </Descriptions.Item>
            <Descriptions.Item label="产权面积">
              {houseData.basicInfo.area}㎡
            </Descriptions.Item>
            <Descriptions.Item label="建筑类型">
              {houseData.basicInfo.buildingType}
            </Descriptions.Item>
            <Descriptions.Item label="楼层">
              {houseData.basicInfo.floor}/{houseData.basicInfo.totalFloors}
            </Descriptions.Item>
            <Descriptions.Item label="朝向">
              {houseData.basicInfo.orientation}
            </Descriptions.Item>
            <Descriptions.Item label="装修情况">
              {houseData.basicInfo.decoration}
            </Descriptions.Item>
            <Descriptions.Item label="建造年份">
              {houseData.basicInfo.buildYear}
            </Descriptions.Item>
            <Descriptions.Item label="房屋性质">
              {houseData.basicInfo.propertyType}
            </Descriptions.Item>
            <Descriptions.Item label="产权年限">
              {houseData.basicInfo.propertyRight}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {houseData.basicInfo.createTime}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {houseData.basicInfo.updateTime}
            </Descriptions.Item>
            <Descriptions.Item label="认证状态">
              {houseData.businessInfo.propertyInfo.hasPropertyInfo ? (
                <Button type="link" onClick={handleAuthClick}>
                  已认证
                </Button>
              ) : (
                <Button type="link" onClick={handleGoAuth}>
                  去认证
                </Button>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="核验状态">
              {houseData.businessInfo.authInfo.hasAuthInfo ? (
                <Button type="link" onClick={handleVerifyClick}>
                  已核验
                </Button>
              ) : (
                <Button type="link" onClick={handleGoVerify}>
                  去核验
                </Button>
              )}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 出租信息 */}
        <Card
          title={
            <Space>
              <HomeOutlined />
              <span>出租信息</span>
            </Space>
          }
          extra={
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={handleEditRentalInfo}
            >
              编辑
            </Button>
          }
        >
          {houseData.rentalInfo.rentalType === 'whole' ? (
            <Tabs
              items={[
                {
                  key: 'whole',
                  label: '整租',
                  children: (
                    <Tabs
                      items={[
                        {
                          key: 'basic',
                          label: (
                            <span>
                              <HomeOutlined />
                              房间基础信息
                            </span>
                          ),
                          children: (
                            <Space
                              direction="vertical"
                              size="large"
                              style={{ width: '100%' }}
                            >
                              {/* 房间信息 */}
                              <Card title="房间信息" size="small">
                                <Descriptions column={2} bordered>
                                  <Descriptions.Item label="月租金">
                                    ¥
                                    {
                                      houseData.rentalInfo.wholeRental
                                        .monthlyRent
                                    }
                                  </Descriptions.Item>
                                  <Descriptions.Item label="支付周期">
                                    {
                                      houseData.rentalInfo.wholeRental
                                        .paymentCycle
                                    }
                                  </Descriptions.Item>
                                  <Descriptions.Item label="出租状态">
                                    {
                                      houseData.rentalInfo.wholeRental
                                        .rentalStatus
                                    }
                                  </Descriptions.Item>
                                  <Descriptions.Item label="看房时间">
                                    {
                                      houseData.rentalInfo.wholeRental
                                        .viewingPeriod
                                    }
                                  </Descriptions.Item>
                                  <Descriptions.Item label="可入住时间">
                                    {
                                      houseData.rentalInfo.wholeRental
                                        .moveInDate
                                    }
                                  </Descriptions.Item>
                                </Descriptions>
                              </Card>

                              {/* 租客信息 */}
                              <Card title="租客信息" size="small">
                                <Descriptions column={2} bordered>
                                  <Descriptions.Item label="租户姓名">
                                    {houseData.rentalInfo.wholeRental.tenantInfo
                                      ?.name || '-'}
                                  </Descriptions.Item>
                                  <Descriptions.Item label="租户电话">
                                    {houseData.rentalInfo.wholeRental.tenantInfo
                                      ?.phone || '-'}
                                  </Descriptions.Item>
                                  <Descriptions.Item label="身份证号">
                                    {houseData.rentalInfo.wholeRental.tenantInfo
                                      ?.idCard || '-'}
                                  </Descriptions.Item>
                                  <Descriptions.Item label="合同开始时间">
                                    {houseData.rentalInfo.wholeRental.tenantInfo
                                      ?.contractStartDate || '-'}
                                  </Descriptions.Item>
                                  <Descriptions.Item label="合同结束时间">
                                    {houseData.rentalInfo.wholeRental.tenantInfo
                                      ?.contractEndDate || '-'}
                                  </Descriptions.Item>
                                </Descriptions>
                              </Card>
                            </Space>
                          ),
                        },
                        {
                          key: 'contract',
                          label: (
                            <span>
                              <FileTextOutlined />
                              合同
                            </span>
                          ),
                          children: (
                            <Table
                              columns={contractColumns}
                              dataSource={houseData.businessInfo.contracts}
                              rowKey="id"
                              pagination={false}
                              size="small"
                            />
                          ),
                        },
                        {
                          key: 'bills',
                          label: (
                            <span>
                              <DollarOutlined />
                              账单
                            </span>
                          ),
                          children: (
                            <Table
                              columns={billColumns}
                              dataSource={houseData.businessInfo.bills}
                              rowKey="id"
                              pagination={false}
                              size="small"
                            />
                          ),
                        },
                        {
                          key: 'repairs',
                          label: (
                            <span>
                              <ToolOutlined />
                              维修
                            </span>
                          ),
                          children: (
                            <Table
                              columns={repairColumns}
                              dataSource={houseData.businessInfo.repairs}
                              rowKey="id"
                              pagination={false}
                              size="small"
                            />
                          ),
                        },
                        {
                          key: 'transfers',
                          label: (
                            <span>
                              <SwapOutlined />
                              转租&退租申请
                            </span>
                          ),
                          children: (
                            <Table
                              columns={transferColumns}
                              dataSource={houseData.businessInfo.transfers}
                              rowKey="id"
                              pagination={false}
                              size="small"
                            />
                          ),
                        },
                        {
                          key: 'logs',
                          label: (
                            <span>
                              <HistoryOutlined />
                              操作日志
                            </span>
                          ),
                          children: (
                            <Table
                              columns={logColumns}
                              dataSource={houseData.businessInfo.logs}
                              rowKey="id"
                              pagination={false}
                              size="small"
                            />
                          ),
                        },
                      ]}
                    />
                  ),
                },
              ]}
            />
          ) : (
            <Tabs
              items={houseData.rentalInfo.sharedRooms.map((room: any) => ({
                key: room.id,
                label: `${room.name}（${room.status}）`,
                children: (
                  <Tabs
                    items={[
                      {
                        key: 'basic',
                        label: (
                          <span>
                            <HomeOutlined />
                            房间基础信息
                          </span>
                        ),
                        children: (
                          <Space
                            direction="vertical"
                            size="large"
                            style={{ width: '100%' }}
                          >
                            {/* 房间信息 */}
                            <Card title="房间信息" size="small">
                              <Descriptions column={2} bordered>
                                <Descriptions.Item label="房间类型">
                                  {room.roomType}
                                </Descriptions.Item>
                                <Descriptions.Item label="朝向">
                                  {room.orientation}
                                </Descriptions.Item>
                                <Descriptions.Item label="面积">
                                  {room.area}㎡
                                </Descriptions.Item>
                                <Descriptions.Item label="月租金">
                                  ¥{room.monthlyRent}
                                </Descriptions.Item>
                                <Descriptions.Item label="出租状态">
                                  {room.status}
                                </Descriptions.Item>
                              </Descriptions>
                            </Card>

                            {/* 租客信息 */}
                            <Card title="租客信息" size="small">
                              <Descriptions column={2} bordered>
                                <Descriptions.Item label="租户姓名">
                                  {room.tenantInfo?.name || '-'}
                                </Descriptions.Item>
                                <Descriptions.Item label="租户电话">
                                  {room.tenantInfo?.phone || '-'}
                                </Descriptions.Item>
                                <Descriptions.Item label="身份证号">
                                  {room.tenantInfo?.idCard || '-'}
                                </Descriptions.Item>
                                <Descriptions.Item label="合同开始时间">
                                  {room.tenantInfo?.contractStartDate || '-'}
                                </Descriptions.Item>
                                <Descriptions.Item label="合同结束时间">
                                  {room.tenantInfo?.contractEndDate || '-'}
                                </Descriptions.Item>
                              </Descriptions>
                            </Card>
                          </Space>
                        ),
                      },
                      {
                        key: 'contract',
                        label: (
                          <span>
                            <FileTextOutlined />
                            合同
                          </span>
                        ),
                        children: (
                          <Table
                            columns={contractColumns}
                            dataSource={houseData.businessInfo.contracts.filter(
                              (contract: any) =>
                                contract.tenantName === room.tenantInfo?.name,
                            )}
                            rowKey="id"
                            pagination={false}
                            size="small"
                          />
                        ),
                      },
                      {
                        key: 'bills',
                        label: (
                          <span>
                            <DollarOutlined />
                            账单
                          </span>
                        ),
                        children: (
                          <Table
                            columns={billColumns}
                            dataSource={houseData.businessInfo.bills}
                            rowKey="id"
                            pagination={false}
                            size="small"
                          />
                        ),
                      },
                      {
                        key: 'repairs',
                        label: (
                          <span>
                            <ToolOutlined />
                            维修
                          </span>
                        ),
                        children: (
                          <Table
                            columns={repairColumns}
                            dataSource={houseData.businessInfo.repairs}
                            rowKey="id"
                            pagination={false}
                            size="small"
                          />
                        ),
                      },
                      {
                        key: 'transfers',
                        label: (
                          <span>
                            <SwapOutlined />
                            转租&退租申请
                          </span>
                        ),
                        children: (
                          <Table
                            columns={transferColumns}
                            dataSource={houseData.businessInfo.transfers.filter(
                              (transfer: any) =>
                                transfer.tenantName === room.tenantInfo?.name,
                            )}
                            rowKey="id"
                            pagination={false}
                            size="small"
                          />
                        ),
                      },
                      {
                        key: 'logs',
                        label: (
                          <span>
                            <HistoryOutlined />
                            操作日志
                          </span>
                        ),
                        children: (
                          <Table
                            columns={logColumns}
                            dataSource={houseData.businessInfo.logs}
                            rowKey="id"
                            pagination={false}
                            size="small"
                          />
                        ),
                      },
                    ]}
                  />
                ),
              }))}
            />
          )}
        </Card>

        {/* 经营信息 */}
        <Card
          title={
            <Space>
              <HomeOutlined />
              <span>经营信息</span>
            </Space>
          }
        >
          <Tabs
            items={[
              {
                key: 'broker_contract',
                label: '经纪人合同',
                children: (
                  <Table
                    columns={[
                      {
                        title: '合同编号',
                        dataIndex: 'contractNo',
                        key: 'contractNo',
                      },
                      {
                        title: '经纪人姓名',
                        dataIndex: 'brokerName',
                        key: 'brokerName',
                      },
                      {
                        title: '合同类型',
                        dataIndex: 'contractType',
                        key: 'contractType',
                      },
                      {
                        title: '开始时间',
                        dataIndex: 'startDate',
                        key: 'startDate',
                      },
                      {
                        title: '结束时间',
                        dataIndex: 'endDate',
                        key: 'endDate',
                      },
                      {
                        title: '佣金比例',
                        dataIndex: 'commissionRate',
                        key: 'commissionRate',
                        render: (rate: number) => `${rate}%`,
                      },
                      {
                        title: '状态',
                        dataIndex: 'status',
                        key: 'status',
                        render: (status: string) => (
                          <Tag
                            color={status === '生效中' ? 'green' : 'default'}
                          >
                            {status}
                          </Tag>
                        ),
                      },
                    ]}
                    dataSource={[
                      {
                        id: 'broker1',
                        contractNo: 'BR2024001',
                        brokerName: '王经纪人',
                        contractType: '独家代理',
                        startDate: '2024-01-01',
                        endDate: '2024-12-31',
                        commissionRate: 5,
                        status: '生效中',
                      },
                    ]}
                    rowKey="id"
                    pagination={false}
                    size="small"
                  />
                ),
              },
              {
                key: 'business_bills',
                label: '账单',
                children: (
                  <Table
                    columns={billColumns}
                    dataSource={houseData.businessInfo.bills}
                    rowKey="id"
                    pagination={false}
                    size="small"
                  />
                ),
              },
              {
                key: 'cleaning',
                label: '清洁',
                children: (
                  <Table
                    columns={[
                      {
                        title: '清洁类型',
                        dataIndex: 'type',
                        key: 'type',
                      },
                      {
                        title: '清洁人员',
                        dataIndex: 'cleaner',
                        key: 'cleaner',
                      },
                      {
                        title: '清洁时间',
                        dataIndex: 'cleanDate',
                        key: 'cleanDate',
                      },
                      {
                        title: '费用',
                        dataIndex: 'cost',
                        key: 'cost',
                        render: (cost: number) => `¥${cost}`,
                      },
                      {
                        title: '状态',
                        dataIndex: 'status',
                        key: 'status',
                        render: (status: string) => (
                          <Tag
                            color={status === '已完成' ? 'green' : 'processing'}
                          >
                            {status}
                          </Tag>
                        ),
                      },
                      {
                        title: '备注',
                        dataIndex: 'remark',
                        key: 'remark',
                      },
                    ]}
                    dataSource={[
                      {
                        id: 'clean1',
                        type: '深度清洁',
                        cleaner: '张阿姨',
                        cleanDate: '2024-01-15',
                        cost: 200,
                        status: '已完成',
                        remark: '退租后清洁',
                      },
                    ]}
                    rowKey="id"
                    pagination={false}
                    size="small"
                  />
                ),
              },
            ]}
          />
        </Card>
      </Space>

      {/* 房屋基础信息编辑弹窗 */}
      <HouseFormModal
        visible={houseFormModalVisible}
        onCancel={() => setHouseFormModalVisible(false)}
        onSuccess={handleHouseFormSuccess}
        houseId={params.id}
      />

      {/* 认证信息弹窗 */}
      <Modal
        title="认证信息"
        open={authModalVisible}
        onCancel={() => setAuthModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setAuthModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        <Descriptions column={2} bordered>
          <Descriptions.Item label="产权人">
            {houseData.businessInfo.propertyInfo.propertyOwner}
          </Descriptions.Item>
          <Descriptions.Item label="产权证号">
            {houseData.businessInfo.propertyInfo.propertyCertificate}
          </Descriptions.Item>
          <Descriptions.Item label="产权面积">
            {houseData.businessInfo.propertyInfo.propertyArea}㎡
          </Descriptions.Item>
          <Descriptions.Item label="房屋性质">
            {houseData.businessInfo.propertyInfo.propertyType}
          </Descriptions.Item>
          <Descriptions.Item label="产权年限">
            {houseData.businessInfo.propertyInfo.propertyRight}
          </Descriptions.Item>
          <Descriptions.Item label="购买日期">
            {houseData.businessInfo.propertyInfo.purchaseDate}
          </Descriptions.Item>
          <Descriptions.Item label="购买价格" span={2}>
            ¥
            {houseData.businessInfo.propertyInfo.purchasePrice.toLocaleString()}
          </Descriptions.Item>
        </Descriptions>
      </Modal>

      {/* 核验信息弹窗 */}
      <Modal
        title="核验信息"
        open={verifyModalVisible}
        onCancel={() => setVerifyModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setVerifyModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        <Descriptions column={2} bordered>
          <Descriptions.Item label="核验状态">
            <Tag color="green">
              {houseData.businessInfo.authInfo.authStatus}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="核验日期">
            {houseData.businessInfo.authInfo.authDate}
          </Descriptions.Item>
          <Descriptions.Item label="核验人">
            {houseData.businessInfo.authInfo.authPerson}
          </Descriptions.Item>
          <Descriptions.Item label="核验证号">
            {houseData.businessInfo.authInfo.authCertificate}
          </Descriptions.Item>
          <Descriptions.Item label="核验照片" span={2}>
            {houseData.businessInfo.authInfo.authPhotos.join(', ')}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
    </PageContainer>
  );
};
